import { loginApi } from '@/api/loginApi'
import { getToken, setToken, delToken } from '@/utils/token'
import sessionStore from '@/utils/Store'

export default {
  state: {
    // 底部导航菜单 true显示 false隐藏
    pagefooter: true,
    token: '',
    nickname: '',
    uid: 0
  },
  getters: {
    pagefooter: state => state.pagefooter,
    token: state => state.token != '' ? state.token : getToken(),
    nickname: state => state.nickname != '' ? state.nickname : sessionStore.get('nickname'),
    uid: state => state.token != '' ? state.uid : 0,
  },
  mutations: {
    // 修改底部导航菜单是否显示
    setPageFooter(state, payload = true) {
      state.pagefooter = payload
    },
    // 设置用户登录状态
    setUserLogin(state, payload) {
      // 写以sessionStorage中
      setToken(payload.token)
      // 用户昵称和uid存储到sessionStorage中
      sessionStore.set('nickname', payload.nickname)
      sessionStore.set('uid', payload.uid)
      state.token = payload.token
      state.nickname = payload.nickname
      state.uid = payload.uid
    },
    // 用户退出
    logout(state) {
      delToken()
      sessionStore.remove('nickname')
      sessionStore.remove('uid')
      state.token = ''
      state.nickname = ''
      state.uid = ''
    }
  },
  actions: {
    async loginAction({ commit }, { username, password }) {
      let ret = await loginApi(username, password)
      commit('setUserLogin', ret.data)
      return true;
    }
  }
}